package nr.nodehost;

import java.io.File;
import java.io.FilenameFilter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.nfunk.jep.JEP;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import nr.nodehost.model.Component;
import nr.nodehost.model.Schema;

public abstract class ComponentDeployer {
	public static final int MAX_COMPILE_TIME=30;

	protected Schema schema;
	protected JSONObject executeContext;
	protected JSONObject component;

	//protected ArrayList<String> compileOptions=null;
	
	public ComponentDeployer(JSONObject component,Schema schema,JSONObject executeContext) {
		this.schema=schema;
		this.component=component;
		this.executeContext=executeContext;
	}

	

	public static boolean generateParameterFile(JSONArray globalParams,String componentDir,JSONObject componentParam) {
		boolean result=true;
		try{
			JEP jep = new JEP();
			//JSONArray globalParams=schema.getParams();
			for(int i=0;i<globalParams.size();i++) {
				JSONObject globalParam=globalParams.getJSONObject(i);
				//System.out.format("name:%s value:%f factor:%f\n",globalParam.getString("name"),globalParam.getDouble("value"),globalParam.getDouble("unitFactor"));
		    	jep.addVariable(globalParam.getString("name"),globalParam.getDouble("value")*globalParam.getDouble("unitFactor"));
			}
			//JSONObject componentParam=component.getJSONObject("componentParam");
			JSONObject functionParam=componentParam.getJSONObject("functionParam");
				
			//if(componentParam.getInt("type")==Component.ALGORITHM_COMPONENT) {
			JSONArray controlParams=functionParam.getJSONArray("controlParams");
			File paramFile=new File(componentDir+"/param.ini");
			PrintStream ps=new PrintStream(paramFile);
					
			for(int j=0;j<controlParams.size();j++) {
				JSONObject param=controlParams.getJSONObject(j);
				ps.format("[%s]\n", param.getString("name"));
				ps.format("type=%d\n", param.getInt("type"));
				ps.print("value=");
				String name=param.getString("name");
				double factor=1.0;
				for(int k=0;k<globalParams.size();k++) {
					if(globalParams.getJSONObject(k).getString("name").equals(name)) {
						factor=globalParams.getJSONObject(k).getDouble("unitFactor");
					}
				}
				String[] expressions=param.getString("value").split(",");
				for(int k=0;k<expressions.length;k++) {
					jep.parseExpression(expressions[k]);
					double value=jep.getValue()*factor;
					if(k==expressions.length-1)
						ps.format("%f\n", value);
					else
						ps.format("%f,", value);
				}
				ps.println();
			}
			ps.close();
		}
		catch(Exception e) {
			e.printStackTrace();
			result=false;
		}
		return result;
	}

	


}
